Check if array is sortedΒΆ

Repformance: O(N)
def check_sorted(A, ascending=True):
    # Transform ascending arg into sign:
    # 2 * int(ascending) - 1
    #   int(True)  = 1 => 2*1 - 1 = +1
    #   int(False) = 0 => 2*0 - 1 = -1
    flag = True                     # sorted
    sign = 2 * int(ascending) - 1
    N = len(A)
    for i in range(0, N-1):
        if sign * A[i] > sign * A[i+1]:
            flag = False
            break
    return flag

Tests:

A = [1, 2, 3, 4, 5, 6, 7]
print(check_sorted(A, True))                    # True
A = [7, 6, 5, 4, 3, 2, 1]
print(check_sorted(A, ascending=False))         # True

A = [1, 3, 2, 4, 5, 6, 7]
print(check_sorted(A, True))                    # False
A = [7, 6, 4, 5, 3, 2, 1]
print(check_sorted(A, ascending=False))         # False